//
// Copyright (C) 2009 Ben Jaques.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// - Neither the name of the author nor the names of its contributors may be used
//   to endorse or promote products derived from this software without specific
//   prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

/*
 * AddAppDialog.java
 *
 * Created on Aug 29, 2009, 9:25:36 AM
 */
package uk.co.massycat.appreviewsfinder;

import uk.co.massycat.appreviewsfinder.countries.CountriesManager;
import java.awt.Color;
import java.awt.Component;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.SwingConstants;

/**
 *
 * @author ben
 */
public class AddAppDialog extends javax.swing.JDialog {

    private String mSearchUrl;
    private AppSearchResult mSelectedApp = null;

    class MyCellRenderer implements ListCellRenderer {

        public Component getListCellRendererComponent(JList list,
                Object value,
                int index,
                boolean isSelected,
                boolean cellHasFocus) {
            AppSearchResult result = (AppSearchResult) value;
            if (result.mArt == null && result.mArtURL != null) {
                try {
                    result.mArt = new ImageIcon(new URL(result.mArtURL));
                } catch (Exception e) {
                }
            }
            JLabel label = new JLabel(result.mName + " - by " + result.mArtist,
                    result.mArt, SwingConstants.LEFT);

            label.setOpaque(isSelected);
            if (isSelected) {
                label.setBackground(Color.lightGray);
            }

            return label;
        }
    }

    private String getSearchResults() {
        // Form the iTune Store id
        int itunes_code = CountriesManager.getManager().getITunesCodeForCountry(AppPreferences.getPreferences().getSearchCountry());
        String iTunesCode = Integer.toString(itunes_code) + ",2";

        String result_xml = Utilities.connectAndGetResponse(mSearchUrl, iTunesCode);

        //System.out.println("Search results:\n" + result_xml);

        return result_xml;
    }

    public AppSearchResult getResult() {
        return mSelectedApp;
    }

    /** Creates new form AddAppDialog */
    public AddAppDialog(java.awt.Dialog parent, boolean modal, String search_url) {
        super(parent, modal);
        initComponents();

        mSearchUrl = new String(search_url);
        mOkButton.setEnabled(false);
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        mCancelButton = new javax.swing.JButton();
        mOkButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        mAppsList = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Add App");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setLayout(new java.awt.BorderLayout());

        mCancelButton.setText("Cancel");
        mCancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mCancelButtonActionPerformed(evt);
            }
        });
        jPanel2.add(mCancelButton);

        mOkButton.setText("Ok");
        mOkButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mOkButtonActionPerformed(evt);
            }
        });
        jPanel2.add(mOkButton);

        jPanel1.add(jPanel2, java.awt.BorderLayout.SOUTH);

        mAppsList.setModel(new javax.swing.DefaultListModel());
        mAppsList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        mAppsList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                mAppsListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(mAppsList);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void mCancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mCancelButtonActionPerformed
        mSelectedApp = null;
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_mCancelButtonActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // perform the search and fill out the list with the results
        String xml = getSearchResults();

        AppSearchReader reader = new AppSearchReader(xml);

        // get the result and use them to populate the list
        List<AppSearchResult> apps = reader.getApps();

        //System.out.println("Apps:\n" + apps);

        DefaultListModel model = (DefaultListModel) mAppsList.getModel();
        model.clear();

        mAppsList.setCellRenderer(new MyCellRenderer());

        Iterator<AppSearchResult> iterator = apps.iterator();

        while (iterator.hasNext()) {
            AppSearchResult result = iterator.next();

            if (result.mAppCode >= 0) {
                model.addElement(result);
            }
        }
        mSelectedApp = null;
        mOkButton.setEnabled(false);
    }//GEN-LAST:event_formWindowOpened

    private void mOkButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mOkButtonActionPerformed
        mSelectedApp = (AppSearchResult) mAppsList.getSelectedValue();
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_mOkButtonActionPerformed

    private void mAppsListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_mAppsListValueChanged
        if (evt.getValueIsAdjusting() == false) {

            mOkButton.setEnabled(mAppsList.getSelectedIndex() != -1);

        }
    }//GEN-LAST:event_mAppsListValueChanged
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList mAppsList;
    private javax.swing.JButton mCancelButton;
    private javax.swing.JButton mOkButton;
    // End of variables declaration//GEN-END:variables
}
